package com.ruoyi.system.service.impl.fxImpl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.GeneralStatus;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.dto.FxSysUserDto;
import com.ruoyi.system.domain.dto.FxUserDto;
import com.ruoyi.system.domain.fx.FxStore;
import com.ruoyi.system.domain.fx.FxToJoin;
import com.ruoyi.system.domain.fx.FxUser;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.mapper.fx.FxStoreMapper;
import com.ruoyi.system.mapper.fx.FxUserMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.fx.IFxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

import static com.ruoyi.common.constant.Constants.FX_COM;
import static com.ruoyi.common.constant.Constants.HTTPS;
import static com.ruoyi.common.utils.CodeGeneratorUtil.createQrCode;
import static com.ruoyi.common.utils.PageUtils.startPage;


/**
 * 用户Service业务层处理
 *
 * @author ruoyi
 * @date 2024-07-23
 */
@Service
public class FxUserServiceImpl implements IFxUserService {
    @Autowired
    private FxUserMapper fxUserMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private FxStoreMapper fxStoreMapper;

    /**
     * 查询用户
     *
     * @param id 用户主键
     * @return 用户
     */
    @Override
    public FxUser selectFxUserById(Long id) {
        return fxUserMapper.selectFxUserById(id);
    }

    /**
     * 小程序查询用户信息
     *
     * @param userId 系统用户时间
     * @return
     */
    @Override
    public FxUser selectFxUserByUserId(Long userId) {
        return fxUserMapper.selectFxUserByUserId(userId);
    }

    /**
     * 查询用户列表
     *
     * @param fxUser 用户
     * @return 用户
     */
    @Override
    public List<FxUser> selectFxUserList(FxUser fxUser) {
        Long userId = SecurityUtils.getUserId();
        List<Long> role = SecurityUtils.getLoginUser().getUser().getRoles()
                .stream().map(SysRole::getRoleId).collect(Collectors.toList());
        FxUser user = fxUserMapper.selectFxUserByUserId(userId);
        if (role.contains(1L) || role.contains(6L)) {
            startPage();
            List<FxUser> userList = fxUserMapper.selectFxUserList(fxUser);
            return userList; // 超级管理员 看全部
        }
//        if (StringUtils.isNull(fxUser.getDistributionId())) {
//            fxUser.setSysUserid(userId);
//        }
        if (StringUtils.isNull(user)) {
            throw new GlobalException("用户信息错误");
        }
        fxUser.setRoleType(user.getRoleType());
        fxUser.setStoreId(user.getStoreId());
        fxUser.setParentAccountId(user.getParentAccountId());
        List<FxUser> userList = fxUserMapper.selectFxUserList(fxUser);
        return userList;
    }

    /**
     * 以手机号查询用户
     * @param phone
     * @return
     */
    @Override
    public FxUser selectUserByPhone(String phone) {
        return fxUserMapper.selectFxUserByPhone(phone);
    }

    /**
     * 后台新增加用户（店铺新增/供应商新增）
     * @param fxUser
     * @return
     */
    @Override
    @Transactional
    public int insertUserInfo(FxUser fxUser) {
        Long userId = SecurityUtils.getUserId();
        FxUser userfx = fxUserMapper.selectFxUserByUserId(userId);
        List<Long> roles = SecurityUtils.getLoginUser().getUser().getRoles()
                .stream().map(SysRole::getRoleId).collect(Collectors.toList());
        if (roles.contains(1L) || roles.contains(6L)) {
            throw new GlobalException("管理员不能新增用户！");
        }
        // 校验手机号
        String regex = "^1[3-9]\\d{9}$";
        boolean isNum = fxUser.getPhoneNumber().matches(regex);
        if (!isNum) {
            throw new GlobalException("请输入正确的手机号");
        }
        if (StringUtils.isNull(userfx)) {
            throw new GlobalException("用户信息异常");
        }
        SysUser user = new SysUser();
        user.setPhonenumber(fxUser.getPhoneNumber());
        if (!sysUserService.checkPhoneUnique(user))
            throw new GlobalException("新增用户'" + fxUser.getUserName() + "'失败，手机号码已存在");
        String password = SecurityUtils.encryptPassword("123456"); // 默认密码
        SysUser sysUser = new SysUser();
        sysUser.setNickName(fxUser.getUserName());
        if (userfx.getRoleType() == 3L) {
            sysUser.setRoleId(3L);
            fxUser.setParentAccountId(userfx.getParentAccountId());
            fxUser.setRoleType(3L);
            System.out.println("新增供应商用户");
        }
        if (userfx.getRoleType() == 4L) {
            sysUser.setRoleId(4L);
            fxUser.setStoreId(userfx.getStoreId());
            fxUser.setRoleType(4L);
            System.out.println("新增店铺用户");
        }
        sysUser.setUserName(fxUser.getPhoneNumber());
        sysUser.setPhonenumber(fxUser.getPhoneNumber());
        sysUser.setPassword(password);
        sysUserService.insertUserAndRole(sysUser);
        //保存用户信息
        fxUser.setSysUserid(sysUser.getUserId());
        fxUser.setUserPassword(password);
        fxUser.setCreateDate(DateUtils.getNowDate());
        fxUserMapper.insertFxUser(fxUser);
        String code = ThreadLocalRandom.current().nextInt(10000, 100000)+""+fxUser.getId();
        FxUser fxUser1 = new FxUser();
        fxUser1.setId(fxUser.getId());
        fxUser1.setStatus(0);
        fxUser1.setUserCode(Convert.toLong(code));
        return fxUserMapper.updateFxUser(fxUser1);
    }

    /**
     * 新增用户
     *
     * @param fxUser 用户
     * @return 结果
     */
    @Override
    public int insertFxUser(FxUser fxUser) {
//        String password = SecurityUtils.encryptPassword(fxUser.getUserPassword());
//        fxUser.setUserPassword(password);
        fxUser.setCreateDate(DateUtils.getNowDate());
        return fxUserMapper.insertFxUser(fxUser);
    }

    /**
     * 用户页面新增用户
     *
     * @param fxUser 用户
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUserWithoutOne(FxUser fxUser) {
        SysUser user = new SysUser();
        user.setPhonenumber(fxUser.getPhoneNumber());
        if (!sysUserService.checkPhoneUnique(user))
            throw new GlobalException("新增用户'" + fxUser.getUserName() + "'失败，手机号码已存在");
        String password = SecurityUtils.encryptPassword("123456");
        SysUser sysUser = new SysUser();
        sysUser.setNickName(fxUser.getUserName());
        Long roleId = StringUtils.isNull(fxUser.getRoleType()) ? 2L : fxUser.getRoleType();
        sysUser.setRoleId(roleId);
        sysUser.setUserName(fxUser.getPhoneNumber()); // 登录电话
        sysUser.setPhonenumber(fxUser.getPhoneNumber()); // 手机号
        sysUser.setPassword(password); // 面膜
        sysUserService.insertUserAndRole(sysUser);
        if (roleId == 4L) { // 4 为店铺
            FxStore fxStore = new FxStore(); // 新建店铺
            fxStore.setStoreName("未启用店铺");
            fxStore.setStatus(GeneralStatus.休息中.getCode());
            fxStore.setIsInitiate(GeneralStatus.否.getCode()); // 下架
            fxStore.setCreateTime(DateUtils.getNowDate());
            fxStoreMapper.insertFxStore(fxStore);
            fxUser.setStoreId(fxStore.getId());
        }
        //保存用户信息
        fxUser.setSysUserid(sysUser.getUserId());
        fxUser.setUserPassword(password);
        fxUser.setCreateDate(DateUtils.getNowDate());
        fxUserMapper.insertFxUser(fxUser);
        String code = ThreadLocalRandom.current().nextInt(10000, 100000)+""+fxUser.getId(); // 生成用户唯一id
        FxUser fxUser1 = new FxUser();
        fxUser1.setId(fxUser.getId());
        fxUser1.setUserCode(Convert.toLong(code));
        return fxUserMapper.updateFxUser(fxUser1);
    }

    /**
     * 新增门店用户
     * @param fxUser
     * @return
     */
    @Override
    @Transactional
    public int insertStoreUser(FxUser fxUser) {
        SysUser user = new SysUser();
        user.setPhonenumber(fxUser.getPhoneNumber());
        if (!sysUserService.checkPhoneUnique(user))
            throw new GlobalException("新增用户'" + fxUser.getUserName() + "'失败，手机号码已存在");
        String password = SecurityUtils.encryptPassword("123456");
        SysUser sysUser = new SysUser();
        sysUser.setNickName(fxUser.getUserName());
        sysUser.setRoleId(4L);
        sysUser.setUserName(fxUser.getPhoneNumber());
        sysUser.setPhonenumber(fxUser.getPhoneNumber());
        sysUser.setPassword(password);
        sysUserService.insertUserAndRole(sysUser);
        //保存用户信息
        fxUser.setSysUserid(sysUser.getUserId());
        fxUser.setUserPassword(password);
        fxUser.setCreateDate(DateUtils.getNowDate());
        fxUserMapper.insertFxUser(fxUser);
        String code = ThreadLocalRandom.current().nextInt(10000, 100000)+""+fxUser.getId();
        FxUser fxUser1 = new FxUser();
        fxUser1.setId(fxUser.getId());
        fxUser1.setStatus(0);
        fxUser1.setUserCode(Convert.toLong(code));
        return fxUserMapper.updateFxUser(fxUser1);
    }

    /**
     * 小程序新增用户 （成为商家 ，成为供应商）
     * @param fxUserDto
     * @return
     */
    @Override
    public int insertUser(FxUserDto fxUserDto) {

        String password = SecurityUtils.encryptPassword("123456");
        SysUser sysUser = new SysUser();
        sysUser.setNickName(fxUserDto.getName());
        sysUser.setRoleId(fxUserDto.getRoleType());
        sysUser.setUserName(fxUserDto.getPhone());
        sysUser.setPhonenumber(fxUserDto.getPhone());
        sysUser.setPassword(password);
        sysUserService.insertUserAndRole(sysUser);
        FxUser fxUser = new FxUser();
        if (fxUserDto.getRoleType() == 4L) { // 4 为店铺
            FxStore fxStore = new FxStore(); // 新建店铺
            String storeName = fxUserDto.getStoreName();
            fxStore.setPhoneNumber(fxUserDto.getPhone());
            fxStore.setImages(fxUserDto.getStorePhoto());
            fxStore.setStoreName(storeName == null ? "未启用店铺" : storeName);
            fxStore.setStatus(GeneralStatus.审核通过.getCode());
            fxStore.setIsInitiate(GeneralStatus.否.getCode()); // 下架
            fxStore.setCreateTime(DateUtils.getNowDate());
            fxStore.setDetail(fxUserDto.getAddress());
            fxStoreMapper.insertFxStore(fxStore);
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 定义日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
            // 将日期格式化为指定格式的字符串
            String formattedDate = currentDate.format(formatter);
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath() + "/storeBarCode/" + formattedDate;
            String url = HTTPS + FX_COM + "/dist?storeId="+fxStore.getId();
            String qrCodeImgPath = createQrCode(url, filePath);
            String imgUrl = "/profile/upload/storeBarCode/" + formattedDate + qrCodeImgPath;
            fxStore.setStoreQrCodeUrl(imgUrl); //分销二维码
            fxStoreMapper.updateFxStore(fxStore);
            //////////////////
            fxUser.setStoreId(fxStore.getId());
        }
        if (fxUserDto.getRoleType() == 3L) {
            fxUser.setVendorAddress(fxUserDto.getAddress());
            fxUser.setProductName(fxUserDto.getProductName());
        }
        //保存用户信息
        fxUser.setStatus(0);
        fxUser.setRoleType(fxUserDto.getRoleType());
        fxUser.setUserName(fxUserDto.getName());
        fxUser.setPhoneNumber(fxUserDto.getPhone());
        fxUser.setSysUserid(sysUser.getUserId());
        fxUser.setUserPassword(password);
        fxUser.setCreateDate(DateUtils.getNowDate());
        fxUser.setRemark(fxUserDto.getRemark());
        if (fxUserDto.getRoleType() == 3L)
            fxUser.setParentAccountId(fxUserDto.getParentAccountId());
        fxUser.setStatus(1);
        fxUserMapper.insertFxUser(fxUser);
        String code = ThreadLocalRandom.current().nextInt(10000, 100000)+""+fxUser.getId();
        FxUser user = new FxUser();
        user.setId(fxUser.getId());
        user.setUserCode(Convert.toLong(code));
        return fxUserMapper.updateFxUser(user);
    }

    /**
     * 修改用户
     *
     * @param fxUser 用户
     * @return 结果
     */
    @Override
    public int updateFxUser(FxUser fxUser) {
//        String userName = fxUser.getUserName();
//        FxUser info = fxUserMapper.checkUserNameUnique(userName);
        return fxUserMapper.updateFxUser(fxUser);
    }

    /**
     * 获取用户id （以手机号）
     * @param phone
     * @return
     */
    @Override
    public Long getSysUserId(String phone) {
        SysUser sysUser = sysUserMapper.checkPhoneUnique(phone);
        if (StringUtils.isNotNull(sysUser)) {
            return sysUser.getUserId();
        }
        return null;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param fxUser 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(FxUser fxUser)
    {
        Long userId = StringUtils.isNull(fxUser.getId()) ? -1L : fxUser.getId();
        FxUser info = fxUserMapper.checkUserNameUnique(fxUser.getUserName());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 修改用户 同时 修改 sysUser
     *
     * @param fxUser
     * @return
     */
    @Override
    public int updateUser(FxUser fxUser) {
        return fxUserMapper.updateFxUserBySysUserId(fxUser);
    }

    /**
     * 批量删除用户
     *
     * @param ids 需要删除的用户主键
     * @return 结果
     */
    @Override
    public int deleteFxUserByIds(Long[] ids) {
        return fxUserMapper.deleteFxUserByIds(ids);
    }

    /**
     * 删除用户信息
     *
     * @param id 用户主键
     * @return 结果
     */
    @Override
    public int deleteFxUserById(Long id) {
        return fxUserMapper.deleteFxUserById(id);
    }



    /**
     * 加盟通过 创建用户数据
     *
     * @param fxToJoin 参数
     */
    @Override
    public void insertUserToJoin(FxToJoin fxToJoin) {
        FxUser fxUser = fxUserMapper.selectFxUserByPhone(fxToJoin.getPhone());
        SysUser sysUser = sysUserMapper.checkPhoneUnique(fxToJoin.getPhone());

        if (StringUtils.isNull(fxUser) && StringUtils.isNull(sysUser)) {
            FxUserDto fxUserDto = new FxUserDto();
            fxUserDto.setStoreName(fxToJoin.getStoreName());
            fxUserDto.setPhone(fxToJoin.getPhone());
            fxUserDto.setAddress(fxToJoin.getAddress());
            fxUserDto.setName(fxToJoin.getName());
            fxUserDto.setRoleType(Convert.toLong(fxToJoin.getRoleType()));
            fxUserDto.setProductName(fxToJoin.getProductName());
            fxUserDto.setSaleType(fxToJoin.getSaleType());
            fxUserDto.setRemark(fxToJoin.getRemark());
            fxUserDto.setStorePhoto(fxToJoin.getImg());
            fxUserDto.setParentAccountId(fxToJoin.getId());
            insertUser(fxUserDto);
        }else {
            FxStore fxStore = Optional.ofNullable(fxStoreMapper.selectFxStoreById(fxUser.getStoreId())).orElse(new FxStore());
            if (fxToJoin.getRoleType() == 4L) { // 店铺
                fxStore.setStatus(GeneralStatus.审核通过.getCode());
                fxStore.setForbidden(GeneralStatus.存在.getCode());
                if (StringUtils.isNotNull(fxStore.getId())) {
                    fxStore.setUpdateTime(DateUtils.getNowDate());
                    fxStore.setStatus(1L);
                    fxStoreMapper.updateFxStore(fxStore);
                } else {
                    fxStore.setIsInitiate(GeneralStatus.否.getCode());
                    String storeName = fxToJoin.getStoreName();
                    fxStore.setStoreName(storeName == null ? "未启用店铺" : storeName);
                    fxStore.setCreateTime(DateUtils.getNowDate());
                    fxStore.setDetail(fxToJoin.getAddress());
                    fxStore.setPhoneNumber(fxToJoin.getPhone());
                    fxStore.setIntro(fxToJoin.getSaleType());
                    fxStore.setImages(fxToJoin.getImg()); // 添加门店图片
                    fxStoreMapper.insertFxStore(fxStore);
                    // 获取当前日期
                    LocalDate currentDate = LocalDate.now();
                    // 定义日期格式
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                    // 将日期格式化为指定格式的字符串
                    String formattedDate = currentDate.format(formatter);
                    // 上传文件路径
                    String filePath = RuoYiConfig.getUploadPath() + "/storeBarCode/" + formattedDate;
                    String url = HTTPS + FX_COM + "/dist?storeId="+fxStore.getId();
                    String qrCodeImgPath = createQrCode(url, filePath);
                    String imgUrl = "/profile/upload/storeBarCode/" + formattedDate + qrCodeImgPath;
                    fxStore.setStoreQrCodeUrl(imgUrl); //分销二维码
                    fxStoreMapper.updateFxStore(fxStore);
                }

            }
            if (fxToJoin.getRoleType() == 3L) {
                fxUser.setParentAccountId(fxToJoin.getId());
            }
            fxUser.setRoleType(Convert.toLong(fxToJoin.getRoleType()));
            fxUser.setUpdateTime(DateUtils.getNowDate());
            fxUser.setStatus(0);
            fxUser.setStoreId(fxStore.getId());
            fxUser.setParentAccountId(fxToJoin.getId());
            if (StringUtils.isNull(fxUser.getUserCode())) {
                String code = ThreadLocalRandom.current().nextInt(10000, 100000)+""+fxUser.getId();
                fxUser.setUserCode(Convert.toLong(code));
            }
            fxUserMapper.updateFxUser(fxUser);
            sysUser.setRoleId(Convert.toLong(fxToJoin.getRoleType()));
            sysUserRoleMapper.insertUserRole(sysUser.getUserId(), sysUser.getRoleId());
        }
    }



    @Override
    @Transactional
    public int insertSupplierUserWithoutOne(FxUser fxUser) {
        SysUser user = new SysUser();
        user.setPhonenumber(fxUser.getPhoneNumber());
        if (!sysUserService.checkPhoneUnique(user)) {
            throw new GlobalException("新增用户'" + fxUser.getUserName() + "'失败，手机号码已存在");
        }
        String password = SecurityUtils.encryptPassword("123456");
        SysUser sysUser = new SysUser();
        sysUser.setNickName(fxUser.getUserName());
        Long roleId = 3L;
        sysUser.setRoleId(roleId);
        sysUser.setUserName(fxUser.getPhoneNumber());
        sysUser.setNickName(fxUser.getUserName());
        sysUser.setPhonenumber(fxUser.getPhoneNumber());
        sysUser.setPassword(password);
        sysUser.setSex("2");
        sysUser.setParentAccountId(fxUser.getParentAccountId());
        sysUserService.insertUserAndRole(sysUser);



        //保存用户信息
        fxUser.setSysUserid(sysUser.getUserId());
        fxUser.setRoleType(3L);
        fxUser.setUserPassword(password);
        fxUser.setCreateDate(DateUtils.getNowDate());
        fxUserMapper.insertFxUser(fxUser);

        String code = ThreadLocalRandom.current().nextInt(10000, 100000)+""+fxUser.getId();
        FxUser fxUser1 = new FxUser();
        fxUser1.setId(fxUser.getId());
        fxUser1.setUserCode(Convert.toLong(code));
        return fxUserMapper.updateFxUser(fxUser1);
    }

    @Override
    public List<FxSysUserDto> selectSupplier(Long parentAccountId) {
        return sysUserMapper.selectSysUserById(parentAccountId);
    }


    @Override
    public int userUpdate(FxUser fxUser) {
        return fxUserMapper.updateFxUser(fxUser);
    }

    /**
     * 查询分销门店成员数量
     * @param distributionId 分销店铺id
     * @return
     */
    @Override
    public List<FxUser> selectTeamNumber(Long distributionId) {
        return fxUserMapper.selectTeamNumber(distributionId);
    }
}
